package com.hsxshop.controller;

import com.hsxshop.model.News;
import com.hsxshop.model.Pagination;

import com.hsxshop.service.NewsService;
import com.hsxshop.util.*;
import lombok.extern.java.Log;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchongya on 17/7/11.
 */
@RestController
@RequestMapping(value = "/news/")
@Log
public class NewsController {

    @Resource(name="newsService")
    private NewsService newsService;

    @RequestMapping(value = "list", method = RequestMethod.POST,produces= MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String index(@RequestBody Map requestMap ){
        Pagination pagination= PaginationTool.getPagination(requestMap);

        List<News> lists=newsService.findByHQLWithPagination(pagination, SqlTool.returnSql("new News(id,title,url,publishTime)", "News", " where publishTime<?0", "order by id desc"), DateTool.getStringDate());

        return JsonTool.returnListJsonSuccess(lists,pagination);
    }

    @RequestMapping(value = "detail", method = RequestMethod.POST,produces=MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String detail(@RequestBody Map requestMap){

        Integer id=(Integer)requestMap.get("id");

        News news=newsService.getEntity(id);

        return JsonTool.returnObjectJsonSuccess(news);
    }

    @RequestMapping(value = "edit", method = RequestMethod.POST,produces=MediaType.APPLICATION_JSON_UTF8_VALUE,consumes =MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String edit(@RequestBody Map requestMap){
        News news= new News();

        news.setContent(ParamConvertTool.getParamStr(requestMap,"content"));
        news.setId(ParamConvertTool.getParamInt(requestMap,"id"));
        String sql="update News set content=? where id=?";
        if(newsService.execHQL(sql,news.getContent(),news.getId())==1){
            return JsonTool.returnObjectJsonSuccess(null);
        }else{
            return JsonTool.returnObjectJsonError(null);
        }

    }
}
